package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.YddCate;
import com.itheima.ydd.service.ISysRoleService;
import com.itheima.ydd.service.IYddCateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/ydd_cate")
public class YddCateController {
    @Autowired
    private IYddCateService yddCateService;
    @Autowired
    private ISysRoleService sysRoleService;
    @GetMapping("/list")
    public ResultData list(String catename, Long page, Long limit ) {
        Page<YddCate> pageInfo=new Page<>(page,limit);

        LambdaQueryWrapper<YddCate> lqw=new LambdaQueryWrapper<>();
        lqw.like(YddCate::getCatename,catename);
        lqw.orderByDesc(YddCate::getSortNum);
        yddCateService.page(pageInfo,lqw);
        PageResult pageResult = PageResult.init(pageInfo.getTotal(), page, limit, pageInfo.getRecords());
        return ResultData.ok("",pageResult);
    }

    /**
     * 添加
     * @param yddCate
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody YddCate yddCate){
        //yddCate.setDefaultData("1");
        yddCateService.save(yddCate);
        return ResultData.ok("","添加成功");
    }

    /**
     * 根据id获取数据
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(int id){
        YddCate yddCate = yddCateService.getById(id);
        return ResultData.ok("",yddCate);
    }

    /**
     * 修改
     * @param yddCate
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody YddCate yddCate){
        yddCateService.updateById(yddCate);
        return ResultData.ok("","修改成功");

    }

    /**
     * s删除
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResultData del(int id){
        YddCate yddCate = yddCateService.getById(id);
        if ("1".equals(yddCate.getDefaultData())){
            return ResultData.error("删除失败");
        }
        if (sysRoleService.RoleUtils("内容管理","分类管理","删除")){
            yddCateService.removeById(id);
            return ResultData.ok("","删除成功");
        }
        //否则没有权限删除
        return ResultData.error("删除失败，该用户没有权限");

    }

    //获取所以分类
    @GetMapping("all")
    public ResultData all(){
        List<YddCate> list = yddCateService.list();
        return ResultData.ok("查询成功",list);
    }
}
